import 'package:flutter/material.dart';
import 'package:ft_reader/common/utils/constans.dart';

import 'home/book_rank.dart';
import 'home/book_shelf.dart';
import 'home/book_store.dart';
import 'home/book_setting.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState()  => _HomePageState();
}

class _HomePageState extends State<HomePage>
  with AutomaticKeepAliveClientMixin {

  var _currentIndex = 0;

  var _tabs = ["书架", "书城", "排行榜", "设置"];

  List<BottomNavigationBarItem> _bottomBars;

  List<Widget> _pages;

  PageController _pageController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _bottomBars = [
      _initBottomItem(_tabs[0], MyIcon.shelfIcon, MyIcon.shelfIcon),
      _initBottomItem(_tabs[1], MyIcon.storeIcon, MyIcon.storeIcon),
      _initBottomItem(_tabs[2], MyIcon.rankIcon, MyIcon.rankIcon),
      _initBottomItem(_tabs[3], MyIcon.home_setting, MyIcon.home_setting),
    ];
    _pages = [
      BookShelf(),
      BookStore(),
      BookRank(),
      BookSettingPage(),
    ];

    _pageController = new PageController(initialPage: 0);
  }

  // AutomaticKeepAliveClientMixin 切换tab后保留tab的状态，避免initState方法重复调用
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: PageView.builder(
          itemBuilder: (BuildContext context, int index) {
            return _pages[index];
          },
        controller: _pageController,
        physics: NeverScrollableScrollPhysics(),
        itemCount: _tabs.length,
        onPageChanged: (int index) {
            setState(() {
              _currentIndex = index;
            });
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: _bottomBars,
        currentIndex: _currentIndex,
        fixedColor: Theme.of(context).primaryColor,
        type: BottomNavigationBarType.fixed,
        onTap: (index) {
          setState(() {
            _pageController.animateToPage(index,
                duration: Duration(microseconds: 200),
                curve: Curves.linear);
          });
        },
      ),
    );
  }

  BottomNavigationBarItem _initBottomItem(
      String title, IconData icon, IconData activeIcon) {
    return BottomNavigationBarItem(
      icon: Icon(
        icon,
        color: Colors.black54
      ),
      activeIcon: Icon(
          activeIcon
      ),
      title: Text(title)
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

}
